package com.chen.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <b>编码过滤器</b>
 * <p>
 * 描述:<br>
 * 过滤器需要实现Filter接口<br>
 * 本拦截器功能--》设置request和response 的请求为配置中的编码<br>
 * web.xml需要配置初始参数，参数名为encoding
 * @author 威 
 * <br>2018年5月22日 下午7:58:16 
 * @see javax.servlet.Filter	
 * @since 1.0
 */
public class EncodingFilter implements Filter {
	private String encoding;
	@Override
	public void destroy() {
		System.out.println("EncodingFilter--》销毁");
	}
	@Override
	public void doFilter(ServletRequest request, 
			ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("EncodingFilter--》进行拦截编码");
		HttpSession session = ((HttpServletRequest) request).getSession(true); //不存在则新建
		System.out.println("sessionID:"+session.getId());
		Date createTime 	= new Date(session.getCreationTime());
		Date lastAccessTime = new Date(session.getLastAccessedTime());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String pageName 	= ((HttpServletRequest) request).getServletPath();
		Integer visitCount 	= new Integer(0);
		String visitCountKey= "visitCount";
		String userIDkey 	= "userID";
		String userID 		= pageName.substring(1, pageName.length());
		if(session.isNew()){
			System.out.println("是一个新的session");
			session.setAttribute(userIDkey, userID);
		}else {
			visitCount = (Integer) session.getAttribute(visitCountKey);
			visitCount = visitCount+1;
			userID = (String)session.getAttribute(userIDkey);
		}
		session.setAttribute(visitCountKey,  visitCount);
		System.out.println("页面名称："+pageName);
		System.out.println("创建时间："+df.format(createTime));
		System.out.println("最后访问时间："+df.format(lastAccessTime));
		System.out.println("用户ID："+userID);
		System.out.println("访问统计："+visitCount);
		request.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset="+encoding);
		chain.doFilter(request, response);//处理完毕，通过拦截器
	}
	@Override
	public void init(FilterConfig cfg) throws ServletException {
		System.out.println("EncodingFilter--》初始化");
		encoding = cfg.getInitParameter("encoding");
	}
}
